package com.sk.leetcode.arithmetic;

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;

/**
 * 给定一个包含 m x n 个元素的矩阵（m 行, n 列），请按照顺时针螺旋顺序，返回矩阵中的所有元素。
 * 输入:
 * [
 * [ 1, 2, 3 ],
 * [ 4, 5, 6 ],
 * [ 7, 8, 9 ]
 * ]
 * 输出: [1,2,3,6,9,8,7,4,5]
 * <p>
 * 输入:
 * [
 * [1, 2, 3, 4],
 * [5, 6, 7, 8],
 * [9,10,11,12]
 * ]
 * 输出: [1,2,3,4,8,12,11,10,9,5,6,7]
 */
public class Test54 {
    public static void main(String[] args) {
        int[][] matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
        List<Integer> res = spiralOrder(matrix);
        System.out.println(JSON.toJSONString(res));
    }

    public static List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<>();
        if(matrix.length == 0){
            return res;
        }
        int width = matrix.length - 1, widthF = 0;
        int length = matrix[0].length - 1, lengthF = 0;
        boolean left = true, down = false, right = false, up = false;
        int a = 0, b = 0;
        while (true) {
            res.add(matrix[b][a]);
            if(left) {
                if(a < length) {
                    a++;
                } else {
                    if(b < width) {
                        b++;
                        left = false;
                        down = true;
                        widthF++;
                    } else {
                        return res;
                    }
                }
            } else if(down) {
                if(b < width) {
                    b++;
                } else {
                    if(a > lengthF) {
                        a--;
                        down = false;
                        right = true;
                        length--;
                    } else {
                        return res;
                    }
                }
            } else if(right) {
                if(a > lengthF) {
                    a--;
                } else {
                    if(b > widthF) {
                        b--;
                        right = false;
                        up = true;
                        width--;
                    } else {
                        return res;
                    }
                }
            } else if(up) {
                if(b > widthF) {
                    b--;
                } else {
                    if(a < length) {
                        a++;
                        up = false;
                        left = true;
                        lengthF++;
                    } else {
                        return res;
                    }
                }
            }
        }




    }
}
